package com.yunqiao.admin.modules.api.controller;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.ApiResponse;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.R;
import com.yunqiao.service.api.ApplyPartnerService;
import com.yunqiao.service.api.entity.ApplyPartnerEntity;
import com.yunqiao.service.sys.SysUserRoleService;
import com.yunqiao.service.sys.entity.SysUserEntity;
import com.yunqiao.service.sys.entity.SysUserRoleEntity;
import com.yunqiao.service.sys.mapper.SysUserDao;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 合伙人申请表
 *
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2019-03-02 15:04:03
 */
@RestController
@RequestMapping("api/applypartner")
public class ApplyPartnerController {

    @Autowired
    private ApplyPartnerService applyPartnerService;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("api:applypartner:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = applyPartnerService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("api:applypartner:info")
    public R info(@PathVariable("id") Integer id){
        ApplyPartnerEntity applyPartner = applyPartnerService.getById(id);
        return R.ok().put("applyPartner", applyPartner);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("api:applypartner:save")
    public R save(@RequestBody ApplyPartnerEntity applyPartner){
        applyPartnerService.saveAplyPartner(applyPartner);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("api:applypartner:update")
    public R update(@RequestBody ApplyPartnerEntity applyPartner){
        applyPartnerService.updateById(applyPartner);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("api:applypartner:delete")
    public R delete(@RequestBody Integer[] ids){
        applyPartnerService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }


    @PutMapping("/agree/{id}")
    @ApiOperation("同意申请加入合伙人")
    public ApiResponse agree(@PathVariable Long id){
        if (id == null) {
            throw new CustomApiException("ID不能为空");
        }
        applyPartnerService.agree(id);
        return new ApiResponse<>();
    }

    @PostMapping("/refuse")
    @ApiOperation("拒绝加入合伙人")
    public ApiResponse refuse(@RequestBody ApplyPartnerEntity applyPartnerEntity){
        applyPartnerService.refuse(applyPartnerEntity);
        return new ApiResponse<>();
    }
    @GetMapping("getPosition")
    @ApiModelProperty("获取合伙人地理位置")
    public ApiResponse  getPosition() {
        List<Dict> list = applyPartnerService.getPosition();
        return new ApiResponse(list);
    }

    @PostMapping("addApplyPartner")
    @ApiModelProperty("添加代理人")
    @Transactional
    public ApiResponse  addApplyPartner(@RequestBody ApplyPartnerEntity applyPartnerEntity) {
        SysUserEntity sysUserEntity = sysUserDao.selectOne(new QueryWrapper<SysUserEntity>().eq("username", applyPartnerEntity.getPhone()));
        if (sysUserEntity != null) {
            throw new CustomApiException("这个代理商已经存在");
        }

        Integer count = applyPartnerService.count(new QueryWrapper<ApplyPartnerEntity>()
                .eq("province", applyPartnerEntity.getProvince())
                .eq("city", applyPartnerEntity.getCity())
                .eq("area", applyPartnerEntity.getArea()));
        if (count > 0) {
            throw new RuntimeException("这个城市有城市合伙人了");
        }
        if (applyPartnerEntity.getMoneyFee().add(applyPartnerEntity.getSysFee()).doubleValue() >= 1) {
            throw new CustomApiException("参数异常");
        }
        sysUserEntity = new SysUserEntity();
        sysUserEntity.setUsername(applyPartnerEntity.getPhone());
        sysUserEntity.setType(AppConsts.SYS_USER_TYPE_1);
        sysUserEntity.setSalt("YzcmCZNvbXocrsz9dm8e");
        sysUserEntity.setPassword("9ec9750e709431dad22365cabc5c625482e574c74adaebba7dd02f1129e4ce1d");
        sysUserDao.insert(sysUserEntity);
        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
        sysUserRoleEntity.setUserId(sysUserEntity.getUserId());
        sysUserRoleEntity.setRoleId(AppConsts.ROLE_PARTNER_ID);
        sysUserRoleService.save(sysUserRoleEntity);
        applyPartnerEntity.setState(AppConsts.USER_APPLY_PARTNER_STATE_3);
        applyPartnerEntity.setSysUserId(sysUserEntity.getUserId());
        this.applyPartnerService.save(applyPartnerEntity);
        return new ApiResponse();
    }


}
